<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="container">
          <el-form
            inline
            size="small"
            :model="from"
            ref="from"
            :label-position="labelPosition"
            label-width="100px"
          >
            <el-row>
              <el-col :xs="24" :sm="24" :md="24" :lg="18" :xl="18">
                <el-form-item label="数据场：">
                  <!-- <el-select
                    v-model="from.dataFactoryId"
                    placeholder="请选择"
                    class="selWidth"
                    clearable
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    >
                    </el-option>
                  </el-select> -->

                  <UserSearchable
                    v-model="from.dataFactoryId"
                    :type="'datafieldList'"
                  >
                    <template #dropdownTitle>
                      <span>名称</span>
                    </template>
                    <template v-slot:dropdown="{ item }">
                      <span>{{ item.name }}</span>
                    </template>
                  </UserSearchable>
                </el-form-item>
                <el-form-item label="用户：">
                  <UserSearchable v-model="from.userId"></UserSearchable>
                  <!-- <el-input
                    v-model="from.userId"
                    placeholder="请选择用户"
                    @focus="selectUser"
                    clearable
                    class="selWidth"
                  /> -->
                </el-form-item>
                <el-form-item label="账户类型：">
                  <el-select
                    v-model="from.accountType"
                    placeholder="请选择"
                    class="selWidth"
                    clearable
                  >
                    <el-option :value="2" label="模拟账号"></el-option>
                    <el-option :value="1" label="资管账号"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="内外盘：">
                  <el-select
                    v-model="from.tradeType"
                    placeholder="请选择"
                    class="selWidth"
                    clearable
                  >
                    <el-option :value="1" label="国际"></el-option>
                    <el-option :value="2" label="国内"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="状态：">
                  <el-select
                    v-model="from.status"
                    placeholder="请选择"
                    class="selWidth"
                    clearable
                  >
                    <el-option :value="1" label="正常"></el-option>
                    <el-option :value="2" label="停用"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col
                :xs="24"
                :sm="24"
                :md="24"
                :lg="6"
                :xl="6"
                class="text-right from"
              >
                <el-form-item>
                  <el-button
                    class="mr10"
                    size="small"
                    type="primary"
                    icon="el-icon-search"
                    @click="search()"
                    >搜索</el-button
                  >
                  <el-button class="mr10" size="small" icon="el-icon-refresh" @click="reset()"
                    >重置</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="btn_bt">
          <el-button class="mr10" size="small" type="primary" icon="el-icon-circle-plus-outline" @click="add()"
            >新增</el-button
          >
          <el-button class="mr10" size="small" type="danger" icon="el-icon-delete" @click="allDel()"
            >删除</el-button
          >
          <el-button class="mr10" size="small" icon="el-icon-top" @click="exportTable()"
            >导出表格</el-button
          >
        </div>
      </div>
      <el-table border
        ref="table"
        v-loading="loading"
        :data="tableData.data"
        style="width: 100%"
        size="mini"
        @selection-change="onSelectTab"
        highlight-current-row
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="id" label="ID" min-width="80" />
        <el-table-column prop="userId" label="用户UID" min-width="80" />
        <el-table-column prop="nickName" label="用户昵称" min-width="80" />
        <el-table-column prop="phone" label="用户电话" min-width="120" />
        <el-table-column
          prop="dataFactoryName"
          label="数据场"
          min-width="130"
        />
        <el-table-column prop="walletResponses" label="钱包" min-width="200">
          <template slot-scope="scope">
            <div
              v-for="(item, index) in scope.row.walletResponses"
              :key="index"
            >
              <span>{{ item.currencyName }}</span>
              <span style="margin-left: 10px">{{ item.balance }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="lossRevenueDaysCoerceLine"
          label="亏损强平线"
          min-width="80"
        />
        <el-table-column
          prop="lossRevenueDaysForbiddenLine"
          label="亏损禁开线"
          min-width="80"
        />
        <el-table-column
          prop="lossRevenueDaysWarningLine"
          label="亏损警告线"
          min-width="80"
        />
        <el-table-column
          prop="traderConfigTemplateName"
          label="交易员综合配置模板"
          min-width="100"
        />
        <el-table-column
          prop="exchangeFeeTemplateName"
          label="手续费模板"
          min-width="100"
        />
        <el-table-column
          prop="traderRiskTemplateName"
          label="风控模板"
          min-width="80"
        />
        <el-table-column prop="accountType" label="	账户类型" min-width="100">
          <template slot-scope="scope">
            <el-button size="mini" v-if="scope.row.accountType == 1"
              >资管账号</el-button
            >
            <el-button size="mini" v-if="scope.row.accountType == 2"
              >模拟账号</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="tradeType" label="内外盘" min-width="80">
          <template slot-scope="scope">
            <el-button size="mini" v-if="scope.row.tradeType == 1"
              >国际</el-button
            >
            <el-button size="mini" v-if="scope.row.tradeType == 2"
              >国内</el-button
            >
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="80">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" v-if="scope.row.status == 1"
              >正常</el-button
            >
            <el-button type="info" size="mini" v-if="scope.row.status == 2"
              >停用</el-button
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="lastLoginIp"
          label="	最后登录ip"
          min-width="120"
        />
        <el-table-column
          prop="lastLoginTime"
          label="最后登录时间"
          min-width="120"
        />
        <el-table-column prop="remark" label="备注" min-width="100" />
        <el-table-column prop="createTime" label="创建时间" min-width="150" />
        <el-table-column
          label="操作"
          min-width="200"
          fixed="right"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="handleMoney(scope.row)"
              >额度变更</el-button
            >
            <el-button type="text" size="small" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="handleDel(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="[15, 30, 45, 60]"
          :page-size="from.limit"
          :current-page="from.page"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.total"
          @size-change="handleSizeChange"
          @current-change="pageChange"
        />
      </div>
    </el-card>

    <el-dialog
      title="钱包额度变更"
      :visible.sync="mVisible"
      width="40%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form :rules="mrules" ref="mform" :model="mform" label-width="120px">
        <el-form-item label="钱包：" prop="walletResponses">
          <div v-for="(item, index) in mform.walletResponses" :key="index">
            <span>{{ item.currencyName }}</span>
            <span style="margin-left: 10px">{{ item.balance }}</span>
          </div>
        </el-form-item>
        <el-form-item label="币种：" prop="currencyId">
          <el-select v-model="mform.currencyId" placeholder="请选择币种">
            <el-option
              v-for="item in walletResponses"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="进出类型：" prop="inOutType">
          <el-radio-group v-model="mform.inOutType">
            <el-radio :label="1">入额度</el-radio>
            <el-radio :label="2">出额度</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input
            v-model="mform.amount"
            type="number"
            placeholder="请输入金额"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="mClose()">取 消</el-button>
        <el-button type="primary" @click="mSubmit()">确 定</el-button>
      </span>
    </el-dialog>

    <!--用户列表-->
    <el-dialog
      title="用户列表"
      :visible.sync="userVisible"
      width="900px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <user-list
        v-if="userVisible"
        @getTemplateRow="getTemplateRow"
      ></user-list>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userclose()">取 消</el-button>
        <el-button type="primary" @click="usersubmit()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="ruleForm.id ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :rules="rules"
        ref="ruleForm"
        :model="ruleForm"
        label-width="180px"
      >
        <el-form-item label="用户" prop="userId">
          <UserSearchable
            v-model="ruleForm.userId"
            :label="ruleForm.nickName"
          ></UserSearchable>
        </el-form-item>
        <el-form-item
          label="交易员综合配置模板："
          prop="traderConfigTemplateId"
        >
          <el-select
            v-model="ruleForm.traderConfigTemplateId"
            placeholder="请选择交易员综合配置模板"
          >
            <el-option
              v-for="item in traderConfigOptions"
              :key="item.id"
              :label="item.traderConfigTemplateName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手续费模板：" prop="exchangeFeeTemplateId">
          <el-select
            v-model="ruleForm.exchangeFeeTemplateId"
            placeholder="请选择手续费模板"
          >
            <el-option
              v-for="item in exchangeFeeOptions"
              :key="item.id"
              :label="item.exchangeFeeTemplateName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="风控模板：" prop="traderRiskTemplateId">
          <el-select
            v-model="ruleForm.traderRiskTemplateId"
            placeholder="请选择风控模板"
          >
            <el-option
              v-for="item in traderriskOptions"
              :key="item.id"
              :label="item.traderRiskTemplateName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账户类型：">
          <el-radio-group v-model="ruleForm.accountType">
            <el-radio :label="2">模拟账号</el-radio>
            <el-radio :label="1">资管账号</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="内外盘：">
          <el-checkbox-group
            v-model="checkedCities"
            @change="handleCheckedCitiesChange"
          >
            <el-checkbox
              v-for="city in cities"
              :label="city.id"
              :key="city.id"
              >{{ city.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="状态：">
          <el-radio-group v-model="ruleForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注：">
          <el-input type="textarea" v-model="ruleForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close()">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import userList from "@/components/userList";
import UserSearchable from "@/components/UserSearchable";
import {
  traderconfigtemplateGetOption, // 交易员综合配置模版全列表
  exchangefeetemplateGetOption, // 交易员手续费模板全列表
  traderrisktemplateGetOption, // 交易员风控模板全列表
} from "@/api/agent";
import { datafieldGetOption } from "@/api/dataField";
import {
  userListApi,
  traderaccountList,
  traderaccountSave,
  traderaccountInfo,
  traderaccountUpdate,
  traderaccountDelete,
  traderaccountExport,
  sys_dict_dataTypeCurrency,
  traderaccountInOutType,
} from "@/api/user";

export default {
  name: "trader",
  components: {
    userList,
    UserSearchable,
  },
  data() {
    return {
      options: [],
      labelPosition: "right",
      userVisible: false,
      from: {
        dataFactoryId: "",
        userId: "",
        accountType: "",
        tradeType: "",
        status: 1,
        page: 1,
        limit: 15,
      },
      loading: false,
      tableData: {
        data: [],
        total: 0,
      },
      selection: [],
      walletResponses: [],
      mform: {
        traderAccountId: "",
        inOutType: "",
        walletResponses: [],
        currencyId: "",
        amount: "",
      },
      mVisible: false,
      dialogVisible: false,
      exchangeFeeOptions: [],
      traderConfigOptions: [],
      traderriskOptions: [],
      ruleForm: {
        id: "",
        userId: "",
        traderConfigTemplateId: "",
        exchangeFeeTemplateId: "",
        traderRiskTemplateId: "",
        accountType: "",
        tradeType: "",
        status: 1,
        remark: "",
      },
      mrules: {
        currencyId: [
          {
            required: true,
            message: "请选择币种",
            trigger: "change",
          },
        ],
        inOutType: [
          {
            required: true,
            message: "请选择进出类型",
            trigger: "change",
          },
        ],
        amount: [
          {
            required: true,
            message: "请输入金额",
            trigger: "blur",
          },
        ],
      },
      checkedCities: [],
      cities: [
        { id: 1, label: "国际" },
        { id: 2, label: "国内" },
      ],
      rules: {
        userId: [
          {
            required: true,
            message: "请选择用户",
            trigger: "change",
          },
        ],
        traderConfigTemplateId: [
          {
            required: true,
            message: "请选择交易员综合配置模板",
            trigger: "change",
          },
        ],
        exchangeFeeTemplateId: [
          {
            required: true,
            message: "请选择手续费模板",
            trigger: "change",
          },
        ],
        traderRiskTemplateId: [
          {
            required: true,
            message: "请选择风控模板",
            trigger: "change",
          },
        ],
      },
    };
  },
  activated() {
    this.search();
  },
  mounted() {
    traderconfigtemplateGetOption()
      .then((res) => {
        console.log("交易员综合配置模版全列表", res);
        this.traderConfigOptions = res;
      })
      .catch((err) => {
        console.log(err);
      });
    exchangefeetemplateGetOption()
      .then((res) => {
        console.log("交易员手续费模板全列表", res);
        this.exchangeFeeOptions = res;
      })
      .catch((err) => {
        console.log(err);
      });
    traderrisktemplateGetOption()
      .then((res) => {
        console.log("交易员风控模板全列表", res);
        this.traderriskOptions = res;
      })
      .catch((err) => {
        console.log(err);
      });
    datafieldGetOption({})
      .then((res) => {
        console.log("数据场全列表", res);
        this.options = res;
      })
      .catch((err) => {
        console.log(err);
      });
    this.getlist();
  },
  methods: {
    selectUser() {
      this.userVisible = true;
    },
    getTemplateRow(row) {
      this.ruleForm.userId = row.uid;
      this.from.userId = row.uid;
    },
    userclose() {
      this.ruleForm.userId = "";
      this.from.userId = "";
      this.userVisible = false;
    },
    usersubmit() {
      this.userVisible = false;
    },
    search() {
      this.from.page = 1;
      this.from.limit = 15;
      this.getlist();
    },
    reset() {
      this.from = {
        dataFactoryId: "",
        userId: "",
        accountType: "",
        tradeType: "",
        status: 1,
        page: 1,
        limit: 15,
      };
      this.getlist();
    },
    getlist() {
      this.loading = true;
      traderaccountList(this.from)
        .then((res) => {
          this.tableData.data = res.list;
          this.tableData.total = res.total;
          this.loading = false;
        })
        .catch((err) => {
          console.log(err);
          this.loading = false;
        });
    },
    add() {
      this.ruleForm = {
        id: "",
        userId: "",
        traderConfigTemplateId: "",
        exchangeFeeTemplateId: "",
        traderRiskTemplateId: "",
        accountType: "",
        tradeType: "",
        status: 1,
        remark: "",
      };
      this.dialogVisible = true;
    },
    close() {
      this.ruleForm = {
        id: "",
        userId: "",
        traderConfigTemplateId: "",
        exchangeFeeTemplateId: "",
        traderRiskTemplateId: "",
        accountType: "",
        tradeType: "",
        status: 1,
        remark: "",
      };
      this.dialogVisible = false;
    },
    handleCheckedCitiesChange(e) {
      // 单选
      if (e.length === 1) {
        this.ruleForm.tradeType = this.checkedCities[0];
      } else {
        // 多选
        this.ruleForm.tradeType = 3;
      }
    },
    submit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.ruleForm.id) {
            console.log("编辑", this.ruleForm);
            traderaccountUpdate(this.ruleForm)
              .then((res) => {
                console.log(res);
                this.close();
                this.$message.success("编辑成功");
                this.getlist();
              })
              .catch((err) => {
                console.log(err);
                this.$message.error(err);
              });
          } else {
            console.log("新增", this.ruleForm);
            let data = {
              userId: this.ruleForm.userId,
              traderConfigTemplateId: this.ruleForm.traderConfigTemplateId,
              exchangeFeeTemplateId: this.ruleForm.exchangeFeeTemplateId,
              traderRiskTemplateId: this.ruleForm.traderRiskTemplateId,
              accountType: this.ruleForm.accountType,
              tradeType: this.ruleForm.tradeType,
              status: this.ruleForm.status,
              remark: this.ruleForm.remark,
            };
            traderaccountSave(data)
              .then((res) => {
                console.log(res);
                this.close();
                this.$message.success("新增成功");
                this.getlist();
              })
              .catch((err) => {
                console.log(err);
                this.$message.error(err);
              });
          }
        } else {
          this.$message.error("请填写完整信息");
        }
      });
    },
    // 选择
    onSelectTab(selection) {
      this.selection = [];
      selection.forEach((item) => {
        this.selection.push(item.id);
      });
      console.log(this.selection);
    },
    allDel() {
      if (this.selection.length == 0) {
        return this.$message.error("至少选择一项");
      }
      console.log(this.selection);
      this.$confirm("确认删除？")
        .then((_) => {
          traderaccountDelete(this.selection)
            .then((res) => {
              console.log(res);
              this.$message.success("删除成功");
              this.getlist();
            })
            .catch((err) => {
              console.log(err);
              this.$message.error(err);
            });
        })
        .catch((_) => {});
    },
    exportTable() {
      traderaccountExport(this.from)
        .then((res) => {
          console.log("导出表格", res);
          window.open(res.filename);
        })
        .catch((err) => {
          console.log(err);
          this.$message.error(err);
        });
    },
    handleMoney(row) {
      sys_dict_dataTypeCurrency()
        .then((res) => {
          console.log("交易员钱包额度变更币种", res);
          this.walletResponses = res;
        })
        .catch((err) => {
          console.log(err);
        });
      this.mform = {
        traderAccountId: row.id,
        inOutType: "",
        walletResponses: row.walletResponses,
        currencyId: "",
        amount: "",
      };
      this.mVisible = true;
    },
    mClose() {
      this.walletResponses = [];
      this.mform = {
        traderAccountId: "",
        inOutType: "",
        walletResponses: [],
        currencyId: "",
        amount: "",
      };
      this.mVisible = false;
    },
    mSubmit() {
      this.$refs["mform"].validate((valid) => {
        if (valid) {
          console.log("额度变更信息", this.mform);
          let data = {
            traderAccountId: this.mform.traderAccountId,
            currencyId: this.mform.currencyId,
            inOutType: this.mform.inOutType,
            amount: this.mform.amount,
          };
          traderaccountInOutType(data)
            .then((res) => {
              console.log(res);
              this.mClose();
              this.$message.success("成功");
              this.getlist();
            })
            .catch((err) => {
              console.log(err);
              this.$message.error(err);
            });
        } else {
          this.$message.error("请填写完整信息");
        }
      });
    },
    handleEdit(row) {
      console.log("编辑", row);
      traderaccountInfo(row.id)
        .then((res) => {
          console.log("详情", res);
          this.ruleForm = {
            id: res.id,
            userId: res.userId,
            nickName: res.nickName,
            traderConfigTemplateId: res.traderConfigTemplateId,
            exchangeFeeTemplateId: res.exchangeFeeTemplateId,
            traderRiskTemplateId: res.traderRiskTemplateId,
            accountType: Number(res.accountType),
            tradeType: Number(res.tradeType),
            status: Number(res.status),
            remark: res.remark,
          };
          if (res.tradeType == 1) {
            this.checkedCities = [1];
          } else if (res.tradeType == 2) {
            this.checkedCities = [2];
          } else {
            this.checkedCities = [1, 2];
          }
          this.dialogVisible = true;
        })
        .catch((err) => {
          console.log(err);
          this.$message.error(err);
        });
    },
    handleDel(row) {
      this.$confirm("确认删除？")
        .then((_) => {
          console.log("删除", row);
          traderaccountDelete([row.id])
            .then((res) => {
              console.log(res);
              this.$message.success("删除成功");
              this.getlist();
            })
            .catch((err) => {
              console.log(err);
              this.$message.error(err);
            });
        })
        .catch((_) => {});
    },
    pageChange(page) {
      this.from.page = page;
      this.getlist();
    },
    handleSizeChange(val) {
      this.from.limit = val;
      this.getlist();
    },
  },
};
</script>

<style scoped lang="scss">
.btn_bt {
  border-top: 1px dashed #ccc;
  padding-top: 20px;
}
</style>
